var getListTime = ''

function sendCmd(cmd) {
  var body = {"request": cmd};
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      try {
        if(c.status_code == 0){
          alert("命令发送成功")
        }else {
          alert("错误："+c.message)
        }
      } catch (d) {
          alert("错误："+c.message)
      }
  })
}

function getMQTTConfig() {
  var body = {"request": "get_mqtt"};
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        // hideLoading("msg-load");
        if(c.status_code == 0){
          document.getElementById("mqtt-status").innerText = c.mqtt.connected == 1 ? "已连接" : "未连接";
          document.getElementById("mqtt-url").value = c.mqtt.url;
          document.getElementById("mqtt-port").value = c.mqtt.port;
          document.getElementById("mqtt-username").value = c.mqtt.username;
          document.getElementById("mqtt-password").value = c.mqtt.password;
        }
      } catch (d) {
          // showMessage(getPrompt("requestFailed"), 2000)
          alert("错误："+d.message)
      }
  })
}

function postSaveMQTTConfig() {
  // timeoutNum = 0;
  // var mesh_id = document.getElementById("mesh-id").value;
  var mqtt_url = document.getElementById("mqtt-url").value;
  var mqtt_port = document.getElementById("mqtt-port").value;
  var mqtt_user = document.getElementById("mqtt-username").value;
  var mqtt_user_pas = document.getElementById("mqtt-password").value;
  var body = {
                  "request": "set_mqtt",
                  "mqtt":{"url":mqtt_url,"port":parseInt(mqtt_port),"username":mqtt_user,"password":mqtt_user_pas}
              };
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          alert("设置成功")
        } else {
          alert("错误："+c)
        }
      } catch (d) {
        alert("错误："+d.message)
      }
  })
}

function postSaveSerialConfig() {
  var node = document.getElementById("select-serial-node").value;
  var baudrate = document.getElementById("params-select-serial-baudrate").value;
  var parity = document.getElementById("params-select-serial-parity").value;
  var body = {
                  "request": "set_serial",
                  "serial":parseInt(node),
                  "value":baudrate+" 8"+parity+"1"
              };
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          alert("设置成功")
        } else {
          alert("错误："+c)
        }
      } catch (d) {
        alert("错误："+d.message)
      }
  })
}

function getSerialConfig() {
  var node = document.getElementById("select-serial-node").value;
  var body = {
                  "request": "get_serial",
                  "serial":parseInt(node)
              };
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      console.log(c);
      try {
        // hideLoading("msg-load");
        if(c.status_code == 0){
          let params = c.value.split(" ");
          document.getElementById("params-select-serial-baudrate").value = params[0];
          document.getElementById("params-select-serial-parity").value = params[1].slice(1,2);
        }
      } catch (d) {
          // showMessage(getPrompt("requestFailed"), 2000)
          alert("错误："+d.message)
      }
  })
}

function selectSerialNode(params) {
  getSerialConfig();
}

function postSaveDeviceName() {
  var name = document.getElementById("device-name").value;
  var body = {
                  "request": "rename_device",
                  "name":name
              };
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          alert("设置成功")
        } else {
          alert("错误："+c)
        }
      } catch (d) {
        alert("错误："+d.message)
      }
  })
}

function postSaveDevicePosition() {
  var name = document.getElementById("device-position").value;
  var body = {
                  "request": "set_position",
                  "position":name
              };
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      console.log(c);
      try {
        if(c.status_code == 0){
          alert("设置成功")
        } else {
          alert("错误："+c)
        }
      } catch (d) {
        alert("错误："+d.message)
      }
  })
}

function postSaveDeviceMESHID() {
  var meshid = document.getElementById("device-mesh-id").value;
  var body = {
                  "request": "set_mesh_config",
                  "mesh_id":meshid
              };
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          alert("设置成功")
        } else {
          alert("错误："+c)
        }
      } catch (d) {
        alert("错误："+d.message)
      }
  })
}

function postSaveDeviceSN() {
  var sn = document.getElementById("device-sn").value;
  var body = {
                  "request": "set_device_info",
                  "sn":sn
              };
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          alert("设置成功")
        } else {
          alert("错误："+c)
        }
      } catch (d) {
        alert("错误："+d.message)
      }
  })
}

function selectDeviceDebugType() {
  var request = document.getElementById("debug-select-request").value;
  console.log(request);
  switch(request) {
  case "device_set_status":
  document.getElementById("debug-select-node-wrap").hidden = true;
  document.getElementById("debug-select-serial-wrap").hidden = true;
  document.getElementById("debug-select-protocol-wrap").hidden = true;
  document.getElementById("debug-slave-addr-wrap").hidden = true;
  document.getElementById("debug-slave-port-wrap").hidden = true;
  document.getElementById("debug-subdev-addr-wrap").hidden = true;
  document.getElementById("debug-subdev-data-id-wrap").hidden = false;
  document.getElementById("debug-subdev-data-type-wrap").hidden = false;
  document.getElementById("debug-subdev-data-value-wrap").hidden = false;
  break;
  case "device_get_status":
  document.getElementById("debug-select-node-wrap").hidden = true;
  document.getElementById("debug-select-serial-wrap").hidden = true;
  document.getElementById("debug-select-protocol-wrap").hidden = true;
  document.getElementById("debug-slave-addr-wrap").hidden = true;
  document.getElementById("debug-slave-port-wrap").hidden = true;
  document.getElementById("debug-subdev-addr-wrap").hidden = true;
  document.getElementById("debug-subdev-data-id-wrap").hidden = false;
  document.getElementById("debug-subdev-data-type-wrap").hidden = true;
  document.getElementById("debug-subdev-data-value-wrap").hidden = true;
  break;
  case "subdev_get_cids":
  document.getElementById("debug-select-node-wrap").hidden = false;
  document.getElementById("debug-select-serial-wrap").hidden = true;
  document.getElementById("debug-select-protocol-wrap").hidden = true;
  document.getElementById("debug-slave-addr-wrap").hidden = true;
  document.getElementById("debug-slave-port-wrap").hidden = true;
  document.getElementById("debug-subdev-addr-wrap").hidden = true;
  document.getElementById("debug-subdev-data-id-wrap").hidden = true;
  document.getElementById("debug-subdev-data-type-wrap").hidden = true;
  document.getElementById("debug-subdev-data-value-wrap").hidden = true;
  break;
  case "subdev_set_cids":
  document.getElementById("debug-select-node-wrap").hidden = false;
  document.getElementById("debug-select-serial-wrap").hidden = false;
  document.getElementById("debug-select-protocol-wrap").hidden = false;
  document.getElementById("debug-slave-addr-wrap").hidden = false;
  document.getElementById("debug-slave-port-wrap").hidden = false;
  document.getElementById("debug-subdev-addr-wrap").hidden = false;
  document.getElementById("debug-subdev-data-id-wrap").hidden = false;
  document.getElementById("debug-subdev-data-type-wrap").hidden = false;
  document.getElementById("debug-subdev-data-value-wrap").hidden = true;
  break;
  case "subdev_get_data":
  document.getElementById("debug-select-node-wrap").hidden = false;
  document.getElementById("debug-select-serial-wrap").hidden = true;
  document.getElementById("debug-select-protocol-wrap").hidden = true;
  document.getElementById("debug-slave-addr-wrap").hidden = true;
  document.getElementById("debug-slave-port-wrap").hidden = true;
  document.getElementById("debug-subdev-addr-wrap").hidden = false;
  document.getElementById("debug-subdev-data-id-wrap").hidden = false;
  document.getElementById("debug-subdev-data-type-wrap").hidden = true;
  document.getElementById("debug-subdev-data-value-wrap").hidden = true;
  break;
  case "subdev_set_data":
  document.getElementById("debug-select-node-wrap").hidden = false;
  document.getElementById("debug-select-serial-wrap").hidden = true;
  document.getElementById("debug-select-protocol-wrap").hidden = true;
  document.getElementById("debug-slave-addr-wrap").hidden = true;
  document.getElementById("debug-slave-port-wrap").hidden = true;
  document.getElementById("debug-subdev-addr-wrap").hidden = false;
  document.getElementById("debug-subdev-data-id-wrap").hidden = false;
  document.getElementById("debug-subdev-data-type-wrap").hidden = false;
  document.getElementById("debug-subdev-data-value-wrap").hidden = false;
  break;
  case "dlt645_set_addr":
  document.getElementById("debug-select-node-wrap").hidden = true;
  document.getElementById("debug-select-serial-wrap").hidden = false;
  document.getElementById("debug-select-protocol-wrap").hidden = true;
  document.getElementById("debug-slave-addr-wrap").hidden = true;
  document.getElementById("debug-slave-port-wrap").hidden = true;
  document.getElementById("debug-subdev-addr-wrap").hidden = true;
  document.getElementById("debug-subdev-data-id-wrap").hidden = true;
  document.getElementById("debug-subdev-data-type-wrap").hidden = true;
  document.getElementById("debug-subdev-data-value-wrap").hidden = false;
  break;
  case "dlt645_get_addr":
  document.getElementById("debug-select-node-wrap").hidden = true;
  document.getElementById("debug-select-serial-wrap").hidden = false;
  document.getElementById("debug-select-protocol-wrap").hidden = true;
  document.getElementById("debug-slave-addr-wrap").hidden = true;
  document.getElementById("debug-slave-port-wrap").hidden = true;
  document.getElementById("debug-subdev-addr-wrap").hidden = true;
  document.getElementById("debug-subdev-data-id-wrap").hidden = true;
  document.getElementById("debug-subdev-data-type-wrap").hidden = true;
  document.getElementById("debug-subdev-data-value-wrap").hidden = true;
  break;
  case "dlt645_set_baudrate":
  document.getElementById("debug-select-node-wrap").hidden = true;
  document.getElementById("debug-select-serial-wrap").hidden = false;
  document.getElementById("debug-select-protocol-wrap").hidden = true;
  document.getElementById("debug-slave-addr-wrap").hidden = true;
  document.getElementById("debug-slave-port-wrap").hidden = true;
  document.getElementById("debug-subdev-addr-wrap").hidden = false;
  document.getElementById("debug-subdev-data-id-wrap").hidden = true;
  document.getElementById("debug-subdev-data-type-wrap").hidden = true;
  document.getElementById("debug-subdev-data-value-wrap").hidden = false;
  break;
  case "dlt645_reset":
  document.getElementById("debug-select-node-wrap").hidden = true;
  document.getElementById("debug-select-serial-wrap").hidden = false;
  document.getElementById("debug-select-protocol-wrap").hidden = true;
  document.getElementById("debug-slave-addr-wrap").hidden = true;
  document.getElementById("debug-slave-port-wrap").hidden = true;
  document.getElementById("debug-subdev-addr-wrap").hidden = false;
  document.getElementById("debug-subdev-data-id-wrap").hidden = true;
  document.getElementById("debug-subdev-data-type-wrap").hidden = true;
  document.getElementById("debug-subdev-data-value-wrap").hidden = true;
  break;
  case "dlt645_set_onoff":
  document.getElementById("debug-select-node-wrap").hidden = true;
  document.getElementById("debug-select-serial-wrap").hidden = false;
  document.getElementById("debug-select-protocol-wrap").hidden = true;
  document.getElementById("debug-slave-addr-wrap").hidden = true;
  document.getElementById("debug-slave-port-wrap").hidden = true;
  document.getElementById("debug-subdev-addr-wrap").hidden = false;
  document.getElementById("debug-subdev-data-id-wrap").hidden = true;
  document.getElementById("debug-subdev-data-type-wrap").hidden = true;
  document.getElementById("debug-subdev-data-value-wrap").hidden = false;
  break;

  case "get_device_info":
  case "reboot":
  case "reset":
  case "device_get_event":
  case "device_get_scenes":
  document.getElementById("debug-select-node-wrap").hidden = true;
  document.getElementById("debug-select-serial-wrap").hidden = true;
  document.getElementById("debug-select-protocol-wrap").hidden = true;
  document.getElementById("debug-slave-addr-wrap").hidden = true;
  document.getElementById("debug-slave-port-wrap").hidden = true;
  document.getElementById("debug-subdev-addr-wrap").hidden = true;
  document.getElementById("debug-subdev-data-id-wrap").hidden = true;
  document.getElementById("debug-subdev-data-type-wrap").hidden = true;
  document.getElementById("debug-subdev-data-value-wrap").hidden = true;
  break;
  }
}

function generateDeviceRequest() {
  var request = document.getElementById("debug-select-request").value;
  var node = document.getElementById("debug-select-node").value;
  var serial_num = document.getElementById("debug-select-serial").value;
  var protocol = document.getElementById("debug-select-protocol").value;
  var slave_ip = document.getElementById("debug-slave-addr").value.split(",");
  var slave_port = document.getElementById("debug-slave-port").value;
  var addr_list = document.getElementById("debug-subdev-addr").value.split(",");
  var data_type = document.getElementById("debug-subdev-data-type").value;
  var data_id = document.getElementById("debug-subdev-data-id").value.split(",");
  var value = document.getElementById("debug-subdev-data-value").value;
  var req_body;
  switch(request) {
  case "get_device_info":
      req_body = {"request":"get_device_info"};
      break;
  case "device_set_status":
      var cids = new Array();
      for (let index = 0; index < data_id.length; index++) {
          if(data_type == "string"){
              cids.push({"cid": data_id[index], "value": value})
          }else if(data_type == "float"){
              cids.push({"cid": data_id[index], "value": parseFloat(value)})
          }else{
              cids.push({"cid": data_id[index], "value": parseInt(value)})
          }
      }
      req_body = {"request":"set_status","characteristics":cids};
  break;
  case "device_get_status":
      req_body = {"request":"get_status","cids":data_id};
      break;
  case "subdev_get_cids":
      req_body = {"request": "subdev_get_cids", "node":node};
      break;
  case "subdev_set_cids":
      var cids = new Array();
      for (let index = 0; index < addr_list.length; index++) {
          for (let data_id_index = 0; data_id_index < data_id.length; data_id_index++) {
                  var item = {
                      "cid": addr_list[index]+"!"+data_id[data_id_index],
                      "type": data_type,
                      "f": 1.0
                      };
              cids.push(item);
          }
      }
      req_body = {
          "request": "subdev_set_cids",
          "node": node,
          "poll_interval": 1000,
          "protocol": protocol,
          "cids": cids
      };
      if(protocol == "ModbusTCP"){
          req_body["slave_port"] = parseInt(slave_port);
          req_body["slave_ip"] = slave_ip;
      }else{
          req_body["serial"] = parseInt(serial_num);
      }

      break;
  case "subdev_get_data":
      var cids = new Array();
      for (let index = 0; index < addr_list.length; index++) {
          for (let data_id_index = 0; data_id_index < data_id.length; data_id_index++) {
              var item = addr_list[index]+"!"+data_id[data_id_index];
              cids.push(item);
          }
      }
      req_body = {"request":"subdev_get_data","node":node,"cids":cids};
      break;
  case "subdev_set_data":
      var cids = new Array();
      for (let index = 0; index < addr_list.length; index++) {
          for (let data_id_index = 0; data_id_index < data_id.length; data_id_index++) {
              var item = {
                  "cid": addr_list[index]+"!"+data_id[data_id_index],
                  "value": parseInt(value)
              };
              if (data_type == "float"){
                  item["value"] = parseFloat(value);
              }
              cids.push(item);
          }
      }
      req_body = {"request":"subdev_set_data","node":node,"cids":cids};
      break;
  case "dlt645_set_addr":
  req_body = {
              "request": "dtl645_set_params",
              "serial": parseInt(serial_num),
              "subcmd":"set_addr",
              "value": value
          };
      break;
  case "dlt645_get_addr":
  req_body = {
              "request": "dtl645_set_params",
              "serial": parseInt(serial_num),
              "subcmd":"get_addr"
          };
      break;
  case "dlt645_set_baudrate":
  req_body = {
              "request": "dtl645_set_params",
              "serial": parseInt(serial_num),
              "addr": addr_list[0],
              "subcmd":"set_baudrate",
              "value": parseInt(value)
          };
      break;
  case "dlt645_reset":
  req_body = {
              "request": "dtl645_set_params",
              "serial": parseInt(serial_num),
              "addr": addr_list[0],
              "subcmd":"reset",
              "password":"02000000"
          };
      break;
  case "dlt645_set_onoff":
  req_body = {
              "request": "dtl645_set_params",
              "serial": parseInt(serial_num),
              "addr": addr_list[0],
              "subcmd":"set_onoff",
              "password":"02000000",
              "value": parseInt(value)
          };
      break;
  case "device_get_event":
      req_body = {"request": "get_event"}
      break;
  case "device_get_scenes":
      req_body = {"request": "get_scenes"}
      break;
  case "reboot":
  req_body = {"request": "reboot"};
      break;
  case "reset":
  req_body = {"request": "reset"};
      break;
  }
  document.getElementById("debug-req").value = JSON.stringify(req_body,null,4);
}

function sendDeviceRequest() {
  var body = document.getElementById("debug-req").value;
  Ajax.postDeviceRequest("/device_request", body, function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        alert("请求成功")
        document.getElementById("debug-resp")
            .value = JSON.stringify(c,null,4);
      } catch (d) {
          alert("错误："+d.message)
      }
  })
}

function getDeviceInfo() {
  var body = {"request": "get_device_info"};
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          document.getElementById("device-name").value = c.name;
          document.getElementById("device-position").value = c.position;
          document.getElementById("device-mesh-id").value = c.mesh_id;
          document.getElementById("device-sn").value = c.sn;
          document.getElementById("device-trigger-num").innerText = c.mlink_trigger;
          document.getElementById("device-scenes-num").innerText = c.mlink_scenes;
        }
      } catch (d) {
          alert("错误："+d.message)
      }
  })
}

function setDOStatus(ioNum, obj) {

  var body = {"request": "subdev_set_data","node":"n0","cids":[{"cid":ioNum,"value":obj.checked?1:0}]};
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      console.log(c);
      try {
        if(c.status_code == 0){
          alert("设置成功")
        }
      } catch (d) {
          alert("错误："+d.message)
      }
  })
}

function getSubdevIOCidStatus(cids) {
  var body = {"request": "subdev_get_data","node":"n0","cids":cids};
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          for (let index = 0; index < c.data.length; index++) {
            const item = c.data[index];
            switch(item.cid){
              case 'ai01':
                document.getElementById("aiStatus01").innerText = item.value;
                break;
              case 'ai02':
                document.getElementById("aiStatus02").innerText = item.value;
                break;
              case 'ai03':
                document.getElementById("aiStatus03").innerText = item.value;
                break;
              case 'temperature':
                if(item.value < -60) {
                  // 无效
                  document.getElementById("ntcTemp").innerText = "--";
                }else {
                  // 有效
                  document.getElementById("ntcTemp").innerText = item.value;
                }
                break;
              case 'bat_voltage':
                if(item.value > 5) {
                  // 无效
                  document.getElementById("batVoltage").innerText = "--"; 
                }else{
                  // 有效
                  document.getElementById("batVoltage").innerText = item.value;
                }
                break;
              case 'power':
                document.getElementById("powerSource").innerText = item.value==1? "外部供电":"电池供电";
                break;
              case 'di01':
                document.getElementById("diStatus01").checked = item.value==1?true:false;
                break;
              case 'di02':
                document.getElementById("diStatus02").checked = item.value==1?true:false;
                break;
              case 'di03':
                document.getElementById("diStatus03").checked = item.value==1?true:false;
                break;
              case 'di04':
                document.getElementById("diStatus04").checked = item.value==1?true:false;
                break;
              case 'do01':
                document.getElementById("doStatus01").checked = item.value==1?true:false;
                break;
              case 'do02':
                document.getElementById("doStatus02").checked = item.value==1?true:false;
                break;
              case 'do03':
                document.getElementById("doStatus03").checked = item.value==1?true:false;
                break;
              case 'do04':
                document.getElementById("doStatus04").checked = item.value==1?true:false;
                break;
              default:
                console.log(`未知的cid:${item.cid}`);
                break;
            }
          }
        }
      } catch (d) {
          alert("错误："+d.message)
      }
  }) 
}

function getIOStatus() {
  // getListTime = setTimeout(getIOStatus,4000)
  getSubdevIOCidStatus(['ai01','ai02','ai03','bat_voltage','temperature','power','di01','di02','di03','di04','do01','do02','do03','do04'])
}

function setLoraConfig() {
  var body = {
      "request": "set_lora_config",
      "en": document.getElementById("lora-enable").checked?1:0,
      "addr":parseInt(document.getElementById("lora-addr").value),
      "ch": parseInt(document.getElementById("lora-channel").value),
      "sp": parseInt(document.getElementById("select-lora-speed").value),
      "pwr": parseInt(document.getElementById("select-lora-power").value),
    };

  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          alert("设置成功")
        }
      } catch (d) {
          alert("错误："+d.message)
      }
  }) 
}

function getLoraConfig() {
  var body = {"request": "get_lora_config"};
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          document.getElementById("lora-enable").checked = c.en==1?true:false;
          document.getElementById("lora-addr").value = c.addr;
          document.getElementById("lora-channel").value = c.ch;
          document.getElementById("select-lora-speed").value = c.sp;
          document.getElementById("select-lora-power").value = c.pwr;
        }
      } catch (d) {
          alert("错误："+d.message)
      }
  }) 
}

function setSNTPConfig() {
  var body = {
    "request": "set_sntp_config",
    "en": document.getElementById("sntp-enable").checked?1:0,
  };

  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          alert("设置成功")
        }
      } catch (d) {
          alert("错误："+d.message)
      }
  }) 
}

function getSNTPConfig() {
  var body = {"request": "get_sntp_config"};
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          document.getElementById("sntp-enable").checked = c.en==1?true:false;
        }
      } catch (d) {
          alert("get_sntp_config 错误："+d.message)
      }
  }) 
}

function getDateTime() {
  var body = {"request": "get_date_time"};
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      console.log(c);
      try {
        if(c.status_code == 0){
          // "2024-09-10 15:43:23"
          var data_time = c.date.split(" ");
          console.log(data_time[0],data_time[1]);
          document.getElementById("dateInput").value = data_time[0];
          document.getElementById("timeInput").value = data_time[1];
        }
      } catch (d) {
          alert("get_date_time 错误："+d.message)
      }
  }) 
}

function setDateTime() {
  const date = document.getElementById('dateInput').value;
  const time = document.getElementById('timeInput').value;
  const date_time = `${date} ${time}:00`;
  console.log(`设置的日期时间为：${date_time}`);
  var body = {
    "request": "set_date_time",
    "date": date_time
  };

  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          alert("设置成功")
        }
      } catch (d) {
          alert("错误："+d.message)
      }
  }) 
}

function cidsProtocolChange() {
  var protocol = document.getElementById("cids-select-protocol").value;
  switch(protocol) {
  case "NONE":
    document.getElementById("cids-select-serial-wrap").hidden = true;
    document.getElementById("cids-select-slave-addr-wrap").hidden = true;
    document.getElementById("cids-select-slave-port-wrap").hidden = true;
    break;
  case "ModbusRTU":
  case "ModbusASCII":
  case "DLT645-07":
  case "DLT645-97":
  case "CJT188-04":
    document.getElementById("cids-select-serial-wrap").hidden = false;
    document.getElementById("cids-select-slave-addr-wrap").hidden = true;
    document.getElementById("cids-select-slave-port-wrap").hidden = true;
    break;
  case "ModbusTCP":
  case "ModbusUDP":
    document.getElementById("cids-select-serial-wrap").hidden = true;
    document.getElementById("cids-select-slave-addr-wrap").hidden = false;
    document.getElementById("cids-select-slave-port-wrap").hidden = false;
    break;
  }
}

function createRowForCids(cid_id, cid_type, cid_factor, max_inr, change_val, name) {
  // 创建一个新的div用于封装一行的输入框
  const rowDiv = document.createElement('div');
  rowDiv.classList.add("form-row");

  // CID 输入框
  const cidInput = document.createElement('input');
  cidInput.classList.add("form-column");
  cidInput.name = 'form-cids-cid';
  cidInput.type = 'text';
  cidInput.value = cid_id;  // 设置初始值
  rowDiv.appendChild(cidInput);

  // 数据类型输入框,u16，u32，i16，i32，float
  const selectElement = document.createElement('select');
  selectElement.classList.add("form-column");
  selectElement.name = 'form-cids-data-type';
  rowDiv.appendChild(selectElement);
  const option1 = document.createElement('option');
  option1.value = 'u16';
  option1.textContent = `u16`;
  selectElement.appendChild(option1);
  const option2 = document.createElement('option');
  option2.value = 'u32';
  option2.textContent = `u32`;
  selectElement.appendChild(option2);
  const option3 = document.createElement('option');
  option3.value = 'i16';
  option3.textContent = `i16`;
  selectElement.appendChild(option3);
  const option4 = document.createElement('option');
  option4.value = 'i32';
  option4.textContent = `i32`;
  selectElement.appendChild(option4);
  const option5 = document.createElement('option');
  option5.value = 'float';
  option5.textContent = `float`;
  selectElement.appendChild(option5);
  const option6 = document.createElement('option');
  option6.value = 'u32CDAB';
  option6.textContent = `u32CDAB`;
  selectElement.appendChild(option6);
  const option7 = document.createElement('option');
  option7.value = 'i32CDAB';
  option7.textContent = `i32CDAB`;
  selectElement.appendChild(option7);
  const option8 = document.createElement('option');
  option8.value = 'fCDAB';
  option8.textContent = `floatCDAB`;
  selectElement.appendChild(option8);
  const option9 = document.createElement('option');
  option9.value = 'string';
  option9.textContent = `string`;
  selectElement.appendChild(option9);
  selectElement.value = cid_type;  // 设置初始值
  // 系数输入框
  const factorInput = document.createElement('input');
  factorInput.classList.add("form-column");
  factorInput.name = 'form-cids-factor';
  factorInput.type = 'number';  // 使用数字类型以方便用户输入
  factorInput.value = cid_factor;  // 设置初始值
  rowDiv.appendChild(factorInput);
  // 上报周期输入框
  const reportInput = document.createElement('input');
  reportInput.classList.add("form-column");
  reportInput.name = 'form-cids-report-interval';
  reportInput.type = 'number';  // 使用数字类型以方便用户输入
  reportInput.value = max_inr;  // 设置初始值
  rowDiv.appendChild(reportInput);
  // 变化上报阈值输入框
  const changeReportInput = document.createElement('input');
  changeReportInput.classList.add("form-column");
  changeReportInput.name = 'form-cids-change-report-threshold';
  changeReportInput.type = 'number';  // 使用数字类型以方便用户输入
  changeReportInput.value = change_val;  // 设置初始值
  rowDiv.appendChild(changeReportInput);

  // name输入框
  const nameInput = document.createElement('input');
  nameInput.classList.add("form-column");
  nameInput.name = 'form-cids-name';
  nameInput.type = 'text';
  nameInput.value = name;  // 设置初始值
  rowDiv.appendChild(nameInput);
  
  // 当前数值输入框
  const valueInput = document.createElement('input');
  valueInput.classList.add("form-column");
  valueInput.name = 'form-cids-value';
  valueInput.type = 'text';
  valueInput.value = '0';  // 设置初始值
  rowDiv.appendChild(valueInput);

  // 删除按钮
  const delBtn = document.createElement('button');
  delBtn.classList.add("form-column");
  delBtn.textContent = '删除';
  delBtn.onclick = function() {
    rowDiv.remove();
  }
  rowDiv.appendChild(delBtn);

  return rowDiv;
}

function addCidToCidsList() {
  const data_id = document.getElementById('add-cid-id').value;
  const data_type = document.getElementById('add-cid-data-type').value;
  const factor = document.getElementById('add-cid-factor').value;
  const max_inr = document.getElementById('add-cid-max-inr').value;
  const change_val = document.getElementById('add-cid-change-val').value;

  // 判断参数是否为空
  if(data_id == '' || data_type == '' || factor == '' || max_inr == '' || change_val == ''){
    alert('参数不能为空')
    return;
  }
  var cidsAddrForm = document.getElementById('cids-addr-form');
  var rowDiv =createRowForCids(data_id, data_type, factor, max_inr, change_val, "");
  // 将当前行添加到表单容器中
  cidsAddrForm.appendChild(rowDiv);
}

function generateFormFromCIDs(formContainer,cids) {

  const formTitle = document.createElement('div');
  formTitle.classList.add('form-row');

  const titleLabel = document.createElement('label');
  titleLabel.classList.add('form-column');
  titleLabel.textContent = 'CID';
  formTitle.appendChild(titleLabel);

  const typeLabel = document.createElement('label');
  typeLabel.classList.add('form-column');
  typeLabel.textContent = '数据类型';
  formTitle.appendChild(typeLabel);

  const factorLabel = document.createElement('label');
  factorLabel.classList.add('form-column');
  factorLabel.textContent = '系数';
  formTitle.appendChild(factorLabel);

  // 上报周期标签
  const reportLabel = document.createElement('label');
  reportLabel.classList.add('form-column');
  reportLabel.textContent = '上报周期';
  formTitle.appendChild(reportLabel);
  
  // 变化上报阈值标签
  const changeReportLabel = document.createElement('label');
  changeReportLabel.classList.add('form-column');
  changeReportLabel.textContent = '变化上报阈值';
  formTitle.appendChild(changeReportLabel);

  // name标签
  const nameLabel = document.createElement('label');
  nameLabel.classList.add('form-column');
  nameLabel.textContent = '名称';
  formTitle.appendChild(nameLabel);
  
  // 数值标签
  const valueLabel = document.createElement('label');
  valueLabel.classList.add('form-column');
  valueLabel.textContent = '数值';
  formTitle.appendChild(valueLabel);

  const operationLabel = document.createElement('label');
  operationLabel.classList.add('form-column');
  operationLabel.textContent = '操作';
  formTitle.appendChild(operationLabel);

  formContainer.appendChild(formTitle);
  // 为每个cid项创建对应的输入行
  cids.forEach(cidObj => {
      // 创建一个新的div用于封装一行的输入框
      const rowDiv = createRowForCids(cidObj.cid, cidObj.type, cidObj.f, cidObj.max_inr, cidObj.change_val, cidObj.name);
      // 将当前行添加到表单容器中
      formContainer.appendChild(rowDiv);
  });

}


// 获取cid数据
function subdevGetCids() {
  var node = document.getElementById('cids-select-node').value;
  var body = {"request": "subdev_get_cids", "node": node};
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      console.log(c);
      try {
        if(c.status_code == 0){
          document.getElementById('cids-select-protocol').value =  c.protocol;
          document.getElementById('cids-poll-interval').value =  c.poll_interval;
          if(c.protocol == 'ModbusTCP'){
            document.getElementById('cids-slave-addr').value =  c.slave_ip;
            document.getElementById('cids-slave-port').value =  c.slave_port;
          }else{
            document.getElementById('cids-select-serial').value =  c.serial;
          }
          var formContainer = document.getElementById('cids-addr-form');
          formContainer.innerHTML = '';
          generateFormFromCIDs(formContainer, c.cids);
          cidsProtocolChange();
        }else{
          var formContainer = document.getElementById('cids-addr-form');
          formContainer.innerHTML = '';
          alert("获取CID失败或当前设备CID为空")
        }
      } catch (d) {
          alert("错误："+d.message)
      }
  }) 
}

// 设置cid数据
function subdevSetCids() {
  var name = document.getElementsByName('form-cids-name');
  var cids = document.getElementsByName('form-cids-cid');
  var data_types = document.getElementsByName('form-cids-data-type');
  var factor = document.getElementsByName('form-cids-factor');
  var max_inr = document.getElementsByName('form-cids-report-interval');
  var change_val = document.getElementsByName('form-cids-change-report-threshold');
  var body = {
    "request": "subdev_set_cids",
    "node": document.getElementById('cids-select-node').value,
    "protocol": document.getElementById('cids-select-protocol').value,
    "poll_interval": parseInt(document.getElementById('cids-poll-interval').value),
    "cids": []
  };

  if(body.protocol == 'ModbusTCP'){
    body.slave_ip = document.getElementById('cids-slave-addr').value.split(',');
    body.slave_port = parseInt(document.getElementById('cids-slave-port').value);
  }else{
    body.serial = parseInt(document.getElementById('cids-select-serial').value);
  }

  for (let index = 0; index < cids.length; index++) {
    // 判断参数是否为空
    if(cids[index].value == '' || data_types[index].value == '' || factor[index].value == '' || max_inr[index].value == '' || change_val[index].value == ''){
      alert('参数不能为空')
      return;
    }
    body.cids.push({
      "name": name[index].value,
      "cid": cids[index].value,
      "type": data_types[index].value,
      "f": parseFloat(factor[index].value),
      "max_inr": parseInt(max_inr[index].value),
      "change_val": parseFloat(change_val[index].value)
    });
  }
  
  console.log(JSON.stringify(body));
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      console.log(c);
      try {
        if(c.status_code == 0){
          alert("设置成功")
          sendCmd('reboot')
        }else{
          alert("设置失败")
        }
      } catch (d) {
          alert("错误："+d.message)
      }
  });
}


// 获取cid数据
function getSubdevCidStatus() {
  var cids = [];
  var node = document.getElementById('cids-select-node').value;
  var valueInput = document.getElementsByName('form-cids-value');
  var cidInputs = document.getElementsByName('form-cids-cid');
  for (let index = 0; index < cidInputs.length; index++) {
    const cid = cidInputs[index].value;
    cids.push(cid);
  }
  var body = {"request": "subdev_get_data","node":node,"cids":cids};
  Ajax.postDeviceRequest(COM_CONSTANT.POST_DEVICE_REQUEST_URL, JSON.stringify(body), function(c) {
      c = JSON.parse(c);
      // console.log(c);
      try {
        if(c.status_code == 0){
          for (let index = 0; index < c.data.length; index++) {
            const result_cid = c.data[index].cid;
            const result_value = c.data[index].value;
            try {
              if(c.data[index].error == 1){
                valueInput[index].value = 'none';
              }
              else{
                valueInput[index].value = result_value;
              }
            }
            catch (e) {
            }
          }
        }
      } catch (d) {
          alert("错误："+d.message)
      }
  }) 
}

function initHash () {
  console.log('页面第一次加载')

  const leftMenuElement = document.getElementById('idLeftMenuDevice');
  leftMenuElement.classList.add('content');

  selectTitle(document.getElementsByClassName('header-title-one')[0])
  selectContent('devInfoShow')

  cidsProtocolChange()
  selectDeviceDebugType()
  
  getDeviceInfo();
  getMQTTConfig();
  getSerialConfig();


}
